// 活动清单
import React, { useEffect, useRef } from 'react'
import moment from 'moment'
import useKeepState from 'use-keep-state'
import MyTable from '../../../components/table/table'
import CreateActivity from './createActivity/createactivity'
import {
  getActivities,
  deleteActivities,
  updateActivities,
} from '../../../request/activities'
import { DatePicker, Button, Tag, Form, Popconfirm } from 'antd'

const { RangePicker } = DatePicker
const DATE_FORMAT = 'YYYY-MM-DD'
const STATUS: any = {
  1: { text: '进行中', color: 'volcano' },
  2: { text: '已完成', color: '#2db7f5' },
}

interface State {
  showModal: boolean
  currentRowData: { [key: string]: any } | null
}

const initialState: State = {
  showModal: false,
  currentRowData: null,
}

const Activity: React.FC<{}> = function () {
  const [form] = Form.useForm()
  const [state, setState] = useKeepState(initialState)
  const tableRef = useRef<any>()

  function handleOnSuccess() {
    setState({ showModal: false })
    tableRef.current.getTableData()
  }

  function handleActionButton(type: number, row: any) {
    switch (type) {
      case 0:
        setState({ showModal: true, currentRowData: row })
        break
      case 1:
        deleteActivities(row.id).then(res => {
          if (res.data.success) {
            tableRef.current.getTableData()
          }
        })
        break
      case 2:
        updateActivities(row.id, { status: 2 }).then(res => {
          if (res.data.success) {
            tableRef.current.getTableData()
          }
        })
        break
      default:
    }
  }

  const tableColumns = [
    {
      title: '序号',
      width: 60,
      render: (currentRowValue: any, currentRowData: any, index: number) =>
        index + 1,
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 90,
      align: 'center',
      render: (status: number) => (
        <Tag color={STATUS[status].color}>{STATUS[status].text}</Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      width: 170,
      align: 'center',
    },
    {
      title: '活动内容',
      dataIndex: 'content',
      className: 'wbba',
    },
    {
      title: '操作',
      width: 250,
      align: 'center',
      fixed: 'right',
      render: (row: any) => (
        <>
          <Button onClick={handleActionButton.bind(null, 0, row)}>编辑</Button>
          <Popconfirm
            title="您确定要删除吗"
            onConfirm={handleActionButton.bind(null, 1, row)}
            placement="bottomLeft"
            okType="danger"
          >
            <Button>删除</Button>
          </Popconfirm>
          <Button
            onClick={handleActionButton.bind(null, 2, row)}
            disabled={row.status === 2}
          >
            完成
          </Button>
        </>
      ),
    },
  ]

  function getData() {
    tableRef.current.getTableData()
  }

  function getActivitiesList(params: any) {
    const values = form.getFieldsValue()
    if (values.date && values.date.length === 2) {
      params.startDate = values.date[0].format(DATE_FORMAT)
      params.endDate = values.date[1].format(DATE_FORMAT)
    }
    return getActivities(params).then(res => {
      if (res.data.success) {
        res.data.data.rows = res.data.data.rows.map((item: any) => {
          item.createdAt = moment(item.createdAt).format('YYYY-MM-DD HH:mm')
          return item
        })
      }
      return res
    })
  }

  function initParams() {
    // 设置为今年一月1日上午 12:00
    const startDate = moment().startOf('year')
    // 设置为今年的 12 月 31 日 23:59:59.999
    const endDate = moment().endOf('year')
    form.setFieldsValue({
      date: [startDate, endDate],
    })
    tableRef?.current?.getTableData()
  }

  useEffect(() => {
    initParams()
  }, [])
  return (
    <div className="activities">
      <div className="query-panel">
        {/* inline是表单元素都在一行 */}
        <Form
          form={form}
          layout="inline"
          onValuesChange={() => tableRef?.current?.getTableData()}
        >
          <Form.Item name="date" label="查询日期">
            <RangePicker allowClear></RangePicker>
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={getData}>
              查询
            </Button>
            <Button onClick={initParams}>重置</Button>
          </Form.Item>
        </Form>
      </div>
      <MyTable
        ref={tableRef}
        getTableData={getActivitiesList}
        columns={tableColumns}
        onAdd={() =>
          setState({
            showModal: true,
            currentRowData: null,
          })
        }
        onDelete={deleteActivities}
      ></MyTable>
      <CreateActivity
        visible={state.showModal}
        onSuccess={handleOnSuccess}
        onCancel={() => setState({ showModal: false })}
        rowData={state.currentRowData}
      ></CreateActivity>
    </div>
  )
}

export default Activity
